package com.android.common.utils.media.screen;

import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.IBinder;
import com.android.common.constant.Constant;
import com.android.common.mvp.view.ActResultCallback;


public class RecordScreenService extends Service {

    private static Activity mActivity;

    public class MediaProjectionBinder extends Binder {
        public RecordScreenService getService() {
            return RecordScreenService.this;
        }

    }

    /**
     * 绑定Service
     *
     * @param activity           context
     * @param serviceConnection serviceConnection
     */
    public static void bindService(Activity activity, ServiceConnection serviceConnection) {
        mActivity = activity;
        Intent intent = new Intent(activity, RecordScreenService.class);
        activity.bindService(intent, serviceConnection, Service.BIND_AUTO_CREATE);
    }

    /**
     * 解绑Services
     * @param serviceConnection serviceConnection
     */
    public void unbindService(ServiceConnection serviceConnection) {
        mActivity.unbindService(serviceConnection);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new MediaProjectionBinder();
    }

    @Override
    public void onDestroy() {
        destroy();
        super.onDestroy();
    }

    /**
     * 销毁
     */
    private void destroy() {
        if (null != mActivity){
            RecordScreenUtil.getInstance(mActivity).destroy();
            stopForeground(true);
        }
    }


    /**
     * 显示通知栏
     */
    private void showNotification() {
        startForeground(Constant.RECORD_SCREEN_NOTIFICATION_ID, ScreenNotification.createRecordNotification(this));
    }

    public void startScreenRecording(int resultCode, Intent data, RecordScreenCallBack captureCallBack) {
        showNotification();
        RecordScreenUtil.getInstance(mActivity).startCaptureRecording(resultCode,data,captureCallBack);
    }

    public void stopScreenRecording(RecordScreenCallBack captureCallBack) {
        RecordScreenUtil.getInstance(mActivity).stopCaptureRecording(captureCallBack);
        stopForeground(true);
        stopSelf();
    }

    public void permissionMediaProjection(ActResultCallback scanCallback) {
        RecordScreenUtil.getInstance(mActivity).permissionMediaProjection(scanCallback);
    }

}